package repo

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"grpc-comment/initialize"
	"grpc-comment/model"
)

type CommentInterface interface {
	GetComment(params map[string]interface{}, page int64, perPage int64) ([]model.Comment,int,error) //获取评论
	AddComment(comment model.Comment) error //添加评论
}

//返回结构体对象
func NewComment() CommentInterface {
	return &comment{}
}

//bbsComment构体
type comment struct {
}

func (this *comment) GetComment(params map[string]interface{}, page int64, perPage int64) ([]model.Comment,int,error) {
	var (
		info    model.Comment
		records []model.Comment
		total   = 0
	)

	db := initialize.PgDb.Model(&info)

	if params != nil {
		db = db.Where(params)
	}
	//总数
	db.Order("id DESC").Count(&total)

	if page > 0 && perPage > 0 {
		db = db.Limit(perPage).Offset((page - 1) * perPage)
	}

	err := db.Order("id DESC").Find(&records).Error
	if err != nil {
		logrus.Errorf("[获得评论列表失败]-[%s]", err)
		return records, 0, err
	}
	return records, total, nil
}

func (this *comment) AddComment(comment model.Comment) error {
	fmt.Println("comment:",comment)
	if err := initialize.PgDb.Create(&comment).Error; err != nil {
		logrus.Errorf("[新增评论失败]-[%s]", err.Error())
		return err
	}
	return nil
}

//func (this *comment) GetToken(accessToken string) *model.Token {
//	var token model.Token
//	err := this.db.Where("access_token = ?", accessToken).First(&token).Error
//	if err != nil {
//		return nil
//	}
//	return &token
//}
